package excel

import (
	"gitee.com/DengAnbang/Computation/src/dbops"
	"strings"
	"gitee.com/DengAnbang/Computation/src/code"
	"github.com/360EntSecGroup-Skylar/excelize"

	"io"
	"gitee.com/DengAnbang/goutils/utils"
	"fmt"
	"gitee.com/DengAnbang/Computation/src/bean"
)

const sheetName = "数量清单"

//导入excel表,并生成新的树,以及模板
func ImportTree(r io.Reader, treeId string, userId string) error {
	xlsx, err := excelize.OpenReader(r)
	if err != nil {
		return err
	}
	var treeBeanNode = NewTreeNodeManage()
	rows := xlsx.GetRows(sheetName)

	for rowIndex, row := range rows {
		if len(row) <= 0 || row[0] == "" {
			continue
		}
		id := outOfRange(row, 0)
		if strings.HasPrefix(id, "t") {
			err := importTree(&treeBeanNode, int(xlsx.GetRowOutlineLevel(sheetName, rowIndex)), treeId, userId, row)
			if err != nil {
				return err
			}
		} else if strings.HasPrefix(id, "c") {
			err := importTemplate(&treeBeanNode, row)
			if err != nil {
				return err
			}
		}
	}


	return nil
}

//导入树
func importTree(treeBeanNode *TreeNodeManage, depth int, treeID string, userID string, row []string) error {
	treeName := outOfRange(row, 2)
	no := outOfRange(row, 1)
	if treeName == "工程项目分类" {
		return nil
	}
	if treeBeanNode.IsEmpty() {
		err := dbops.DeleteTreeNode(treeID)
		if err != nil {
			return err
		}
		tree, err := dbops.CreateTreeByUuid(treeID, treeName, userID, code.TypeTreeTemplate, "sort", "thisCode", no)
		if err != nil {
			return err
		}
		treeBeanNode.SetRootNode(&tree)
	} else {
		parent := treeBeanNode.GetParentByDepth( depth)
		tree, err := dbops.AddTreeNode(treeName, parent.ThisTreeBean.NodeId, userID, "sort", "thisCode", no)
		if err != nil {
			return err
		}
		treeBeanNode.AddTreeNode(&TreeNode{
			ThisTreeBean: &tree,
			ChildNodes:   make([]*TreeNode, 0),
		}, parent)
	}
	return nil
}

//导入模板
func importTemplate(treeBeanNode *TreeNodeManage, row []string) error {
	treeName := outOfRange(row, 3)
	no := outOfRange(row, 1)
	_, err := dbops.AddTemplateNode(treeBeanNode.LastTreeNode.ThisTreeBean.NodeId, no, treeName, outOfRange(row, 4), outOfRange(row, 5), outOfRange(row, 6), "")
	if err != nil {

		return err
	}
	return nil
}

//获取数组里面的值,防止数组越界
func outOfRange(cells []string, index int) string {
	if len(cells) > index {
		return cells[index]
	}
	return ""
}

//导出树和模板到excel表
func ExportTree(treeId string) (*excelize.File, string, error) {
	if len(treeId) <= 0 {
		return nil, "", bean.NewErrorMessage("树的ID不能为空")
	}
	var treeName string
	treeBean, err := dbops.SelectTreeNode(treeId)
	if err != nil {
		return nil, "", err
	}
	treeName = treeBean.NodeName

	beans, err := dbops.SelectTreeNodeList(treeId, true)
	if err != nil {
		return nil, "", err
	}
	treeBeanNode := NewTreeNodeManage()
	treeBeanNode.SetRootNode(&treeBean)
	treeBeanNode.CreateTree(beans)

	xlsx := excelize.NewFile()
	titleStyle, err := xlsx.NewStyle(`{"font":{"bold":true,"size":10},"alignment":{"horizontal":"center"}}`)
	if err != nil {
		return nil, "", err
	}
	contentStyle, err := xlsx.NewStyle(`{"font":{"size":10},"alignment":{"horizontal":"center"}}`)
	if err != nil {
		return nil, "", err
	}
	xlsx.NewSheet(sheetName)
	writerCellValue(xlsx, titleStyle, sheetName, 1, []string{"ID", "序号", "工程项目分类", "工程项目分类", "单位", "设计量", "价格"})
	xlsx.SetColWidth(sheetName, "C", "D", 20)
	xlsx.SetColWidth(sheetName, "F", "G", 20)
	rowNum := 2
	//表格内容
	for _, treeNode := range treeBeanNode.Beans() {
		writerCellValue(xlsx, contentStyle, sheetName, rowNum, []string{"t" + treeNode.Id, treeNode.No, treeNode.NodeName})
		xlsx.SetRowOutlineLevel(sheetName, rowNum-1, uint8(utils.String2int(treeNode.Depth, 0)))
		rowNum++
		templateBeans, err := dbops.SelectTemplateList(treeNode.NodeId)
		if err != nil {
			return nil, "", err
		}
		for _, t := range templateBeans {
			writerCellValue(xlsx, contentStyle, sheetName, rowNum, []string{"c" + t.Id, t.No, "", t.Name, t.Unit, t.DesignNum, t.Price})
			xlsx.SetRowOutlineLevel(sheetName, rowNum-1, uint8(utils.String2int(treeNode.Depth, 0)+1))
			rowNum++
		}
	}
	err = xlsx.SetSheetPrOptions(sheetName, excelize.OutlineSummaryBelow(false))
	if err != nil {
		return nil, "", err
	}
	xlsx.DeleteSheet("Sheet1")
	// 设置工作簿的默认工作表
	//xlsx.SetActiveSheet(index)
	return xlsx, treeName, nil
}
func writerCellValue(xlsx *excelize.File, styleID int, sheetName string, row int, line []string) {
	for index, value := range line {
		sprint := fmt.Sprint(utils.Int32To26(index+1), row)
		xlsx.SetCellValue(sheetName, sprint, value)
	}
	if styleID != 0 {
		xlsx.SetCellStyle(sheetName, fmt.Sprint(utils.Int32To26(1), row), fmt.Sprint(utils.Int32To26(len(line)), row), styleID)
	}
}

